#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Flask应用模块
包含Web API接口和前端界面
"""

import os
import tempfile
import threading
import time
import sys
import subprocess
import shutil
from flask import Flask, request, send_file, jsonify
from doc_trans import translate_document, get_document_paragraph_count

# 平台检测和兼容性处理
if sys.platform == "win32":
    # Windows系统使用Microsoft Word COM接口
    try:
        import win32com.client
        import pythoncom
        HAS_WIN32COM = True
    except ImportError:
        HAS_WIN32COM = False
        print("警告: 未安装pywin32库，DOC文件转换功能将不可用")
else:
    # Linux/Mac系统使用LibreOffice或在线转换服务
    HAS_WIN32COM = False

app = Flask(__name__)

# 应用启动时自动启动定时清理任务
import atexit

# 在模块导入时启动定时清理任务
cleanup_thread = None
cleanup_running = False
cleanup_lock = threading.Lock()

# 定义定时清理任务函数

def cleanup_old_files():
    """清理extracted_images目录和output目录中的旧文件"""
    current_time = time.time()
    cleanup_interval = 24 * 60 * 60  # 24小时
    
    # 清理extracted_images目录
    extracted_images_dir = "extracted_images"
    if os.path.exists(extracted_images_dir):
        try:
            for root, dirs, files in os.walk(extracted_images_dir):
                for file in files:
                    file_path = os.path.join(root, file)
                    # 检查文件修改时间
                    file_mtime = os.path.getmtime(file_path)
                    if current_time - file_mtime > cleanup_interval:
                        os.unlink(file_path)
                        print(f"定时清理: 已移除旧文件 {file_path}")
            
            # 如果目录为空，删除整个目录
            if not os.listdir(extracted_images_dir):
                shutil.rmtree(extracted_images_dir)
                print("定时清理: 已移除空的extracted_images目录")
        except Exception as e:
            print(f"定时清理extracted_images目录时出错: {e}")
    
    # 清理output目录中的旧文件
    output_dir = "output"
    if os.path.exists(output_dir):
        try:
            for file in os.listdir(output_dir):
                file_path = os.path.join(output_dir, file)
                if os.path.isfile(file_path):
                    # 检查文件修改时间
                    file_mtime = os.path.getmtime(file_path)
                    if current_time - file_mtime > cleanup_interval:
                        os.unlink(file_path)
                        print(f"定时清理: 已移除旧文件 {file_path}")
        except Exception as e:
            print(f"定时清理output目录时出错: {e}")


def cleanup_scheduler_worker():
    """定时清理任务的工作线程"""
    while cleanup_running:
        try:
            # 执行清理
            cleanup_old_files()
            
            # 等待24小时
            time.sleep(24 * 60 * 60)
        except Exception as e:
            print(f"定时清理任务执行出错: {e}")
            # 出错后等待1小时再重试
            time.sleep(60 * 60)

# 启动定时清理任务
def init_cleanup_scheduler():
    """初始化并启动定时清理任务"""
    global cleanup_thread, cleanup_running
    with cleanup_lock:
        if cleanup_thread is None or not cleanup_thread.is_alive():
            cleanup_running = True
            cleanup_thread = threading.Thread(target=cleanup_scheduler_worker, daemon=True)
            cleanup_thread.start()
            print("定时清理任务已启动")

# 停止定时清理任务
def stop_cleanup_scheduler():
    """停止定时清理任务"""
    global cleanup_running
    with cleanup_lock:
        cleanup_running = False
        print("定时清理任务已停止")

# 注册应用退出时的清理函数
atexit.register(stop_cleanup_scheduler)

# 启动定时清理任务
init_cleanup_scheduler()

# 全局变量存储翻译进度（使用线程安全的字典）
progress_data = {}
progress_lock = threading.Lock()

# 全局变量存储正在运行的任务（用于取消功能）
running_tasks = {}
running_tasks_lock = threading.Lock()

# 任务取消标志
cancelled_tasks = set()
cancelled_tasks_lock = threading.Lock()

# 定时清理任务标志
cleanup_thread = None
cleanup_running = False
cleanup_lock = threading.Lock()



def stop_cleanup_scheduler():
    """停止定时清理任务"""
    global cleanup_running, cleanup_thread
    
    with cleanup_lock:
        if not cleanup_running:
            return
        
        cleanup_running = False
        print("定时清理任务已停止")
    
    if cleanup_thread:
        cleanup_thread.join(timeout=10)
        cleanup_thread = None

def convert_doc_to_docx(doc_path):
    """
    将DOC文件转换为DOCX格式（跨平台兼容）
    
    Args:
        doc_path: DOC文件路径
        
    Returns:
        str: 转换后的DOCX文件路径，失败返回None
    """
    docx_path = doc_path.replace('.doc', '.docx')
    
    if sys.platform == "win32" and HAS_WIN32COM:
        # Windows系统使用Microsoft Word COM接口
        try:
            # 初始化COM
            pythoncom.CoInitialize()
            
            # 创建Word应用
            word = win32com.client.Dispatch("Word.Application")
            word.Visible = False
            
            # 打开DOC文件
            doc = word.Documents.Open(doc_path)
            
            # 保存为DOCX格式
            doc.SaveAs(docx_path, FileFormat=16)  # 16代表DOCX格式
            doc.Close()
            
            # 关闭Word应用
            word.Quit()
            pythoncom.CoUninitialize()
            
            print(f"成功将DOC文件转换为DOCX: {docx_path}")
            return docx_path
            
        except Exception as e:
            print(f"DOC文件转换失败: {e}")
            # 清理资源
            try:
                pythoncom.CoUninitialize()
            except:
                pass
    else:
        # Linux/Mac系统使用LibreOffice命令行转换
        try:
            # 检查是否安装了LibreOffice
            result = subprocess.run(['which', 'libreoffice'], capture_output=True, text=True)
            if result.returncode == 0:
                # 使用LibreOffice进行转换
                cmd = [
                    'libreoffice', '--headless', '--convert-to', 'docx',
                    '--outdir', os.path.dirname(docx_path), doc_path
                ]
                result = subprocess.run(cmd, capture_output=True, text=True)
                
                if result.returncode == 0:
                    print(f"使用LibreOffice成功将DOC文件转换为DOCX: {docx_path}")
                    return docx_path
                else:
                    print(f"LibreOffice转换失败: {result.stderr}")
            else:
                print("未找到LibreOffice，无法进行DOC文件转换")
        except Exception as e:
            print(f"Linux系统DOC转换失败: {e}")
    
    return None

# 清理过期任务（超过1小时）
def cleanup_expired_tasks():
    """清理过期任务"""
    current_time = time.time()
    expired_tasks = []
    
    with progress_lock:
        for task_id, task_data in progress_data.items():
            if current_time - task_data.get('timestamp', 0) > 3600:  # 1小时过期
                expired_tasks.append(task_id)
        
        for task_id in expired_tasks:
            del progress_data[task_id]
    
    return len(expired_tasks)

def update_progress(task_id, progress, current, total):
    """更新进度信息"""
    with progress_lock:
        progress_data[task_id] = {
            'progress': progress,
            'current': current,
            'total': total,
            'timestamp': time.time()
        }

@app.route('/progress/<task_id>')
def get_progress(task_id):
    """获取翻译进度"""
    # 清理过期任务
    cleanup_expired_tasks()
    
    with progress_lock:
        if task_id in progress_data:
            return jsonify(progress_data[task_id])
        else:
            return jsonify({'error': '任务不存在或已过期'}), 404

@app.route('/tasks')
def list_tasks():
    """列出所有活跃任务（用于调试）"""
    cleanup_expired_tasks()
    
    with progress_lock:
        active_tasks = {}
        for task_id, task_data in progress_data.items():
            active_tasks[task_id] = {
                'progress': task_data.get('progress', 0),
                'filename': task_data.get('filename', '未知'),
                'timestamp': task_data.get('timestamp', 0)
            }
        
        return jsonify({
            'active_task_count': len(active_tasks),
            'tasks': active_tasks
        })

@app.route('/cancel/<task_id>', methods=['POST'])
def cancel_task(task_id):
    """取消指定的翻译任务"""
    # 检查任务是否存在
    with running_tasks_lock:
        if task_id not in running_tasks:
            return jsonify({'error': '任务不存在或已完成'}), 404
    
    # 标记任务为已取消
    with cancelled_tasks_lock:
        cancelled_tasks.add(task_id)
    
    return jsonify({
        'success': True,
        'message': f'任务 {task_id} 已标记为取消'
    })

@app.route('/cleanup/start', methods=['POST'])
def start_cleanup():
    """手动启动定时清理任务"""
    init_cleanup_scheduler()
    return jsonify({
        'success': True,
        'message': '定时清理任务已启动'
    })

@app.route('/cleanup/stop', methods=['POST'])
def stop_cleanup():
    """手动停止定时清理任务"""
    stop_cleanup_scheduler()
    return jsonify({
        'success': True,
        'message': '定时清理任务已停止'
    })

@app.route('/cleanup/run', methods=['POST'])
def run_cleanup():
    """手动执行一次清理任务"""
    try:
        cleanup_old_files()
        return jsonify({
            'success': True,
            'message': '手动清理任务执行完成'
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'清理任务执行失败: {str(e)}'
        }), 500

@app.route('/cleanup/status', methods=['GET'])
def get_cleanup_status():
    """获取定时清理任务状态"""
    return jsonify({
        'running': cleanup_running,
        'message': '定时清理任务正在运行' if cleanup_running else '定时清理任务已停止'
    })

def translate_task(input_path, output_path, translate_tables, translation_direction, task_id, original_filename):
    """翻译任务线程函数"""
    try:
        # 注册任务到运行任务列表
        with running_tasks_lock:
            running_tasks[task_id] = {
                'input_path': input_path,
                'output_path': output_path,
                'filename': original_filename,
                'start_time': time.time()
            }
        
        # 获取文档总工作量（段落数 + 表格单元格数）
        total_paragraphs = get_document_paragraph_count(input_path, translate_tables)
        
        # 更新初始进度
        update_progress(task_id, 0, 0, total_paragraphs)
        
        # 翻译文档（传递进度回调）
        def progress_callback(progress, current, total):
            # 检查任务是否被取消
            with cancelled_tasks_lock:
                if task_id in cancelled_tasks:
                    raise Exception("翻译任务已被用户取消")
            update_progress(task_id, progress, current, total)
        
        translate_document(input_path, output_path, 
                          translate_tables=translate_tables,
                          translation_direction=translation_direction,
                          progress_callback=progress_callback)
        
        # 标记任务完成
        update_progress(task_id, 100, total_paragraphs, total_paragraphs)
        
        # 清理临时输入文件
        if os.path.exists(input_path):
            os.unlink(input_path)
        
    except Exception as e:
        # 检查是否是取消操作
        with cancelled_tasks_lock:
            if task_id in cancelled_tasks:
                # 标记任务为已取消
                with progress_lock:
                    progress_data[task_id] = {
                        'error': '翻译任务已被用户取消',
                        'progress': 0,
                        'current': 0,
                        'total': 0,
                        'timestamp': time.time(),
                        'filename': original_filename,
                        'cancelled': True
                    }
                # 清理临时文件
                if os.path.exists(input_path):
                    os.unlink(input_path)
                if os.path.exists(output_path):
                    os.unlink(output_path)
            else:
                # 标记任务失败
                with progress_lock:
                    progress_data[task_id] = {
                        'error': str(e),
                        'progress': 0,
                        'current': 0,
                        'total': 0,
                        'timestamp': time.time(),
                        'filename': original_filename
                    }
                
                # 清理临时文件
                if os.path.exists(input_path):
                    os.unlink(input_path)
    finally:
        # 从运行任务列表中移除
        with running_tasks_lock:
            if task_id in running_tasks:
                del running_tasks[task_id]

@app.route('/upload', methods=['POST'])
def upload_file():
    """文件上传和翻译接口"""
    if 'file' not in request.files:
        return jsonify({"error": "未找到文件"}), 400
    
    file = request.files['file']
    if file.filename == '':
        return jsonify({"error": "未选择文件"}), 400
    
    # 获取表格翻译选项
    translate_tables = request.form.get('translate_tables') == 'true'
    # 获取翻译方向选项（默认为英翻中）
    translation_direction = request.form.get('translation_direction', 'en_to_zh')
    
    if file and (file.filename.endswith('.doc') or file.filename.endswith('.docx')):
        # 创建临时文件
        with tempfile.NamedTemporaryFile(suffix='.docx', delete=False) as temp_input:
            file.save(temp_input)
            input_path = temp_input.name
        
        # 如果是DOC文件，先转换为DOCX
        if file.filename.endswith('.doc'):
            print(f"检测到DOC文件，开始转换: {input_path}")
            converted_path = convert_doc_to_docx(input_path)
            if converted_path:
                # 删除原始DOC文件，使用转换后的DOCX文件
                os.remove(input_path)
                input_path = converted_path
                print(f"转换成功，使用文件: {input_path}")
            else:
                # 转换失败，返回错误信息
                os.remove(input_path)
                if sys.platform == "win32":
                    return jsonify({'error': 'DOC文件转换失败，请确保系统安装了Microsoft Word'}), 400
                else:
                    return jsonify({'error': 'DOC文件转换失败，请安装LibreOffice或手动转换为DOCX格式'}), 400
        
        # 准备输出文件路径（使用同级output目录）
        output_filename = f"translated_{os.path.basename(file.filename)}"
        output_path = os.path.join("output", output_filename)
        
        # 确保output目录存在
        os.makedirs("output", exist_ok=True)
        
        # 生成唯一任务ID（时间戳+随机数）
        import random
        task_id = f"{int(time.time() * 1000)}_{random.randint(1000, 9999)}"
        
        # 生成唯一输出文件名（避免冲突）
        unique_output_filename = f"translated_{task_id}_{os.path.basename(file.filename)}"
        unique_output_path = os.path.join("output", unique_output_filename)
        
        # 启动翻译线程
        thread = threading.Thread(
            target=translate_task,
            args=(input_path, unique_output_path, translate_tables, translation_direction, task_id, file.filename)
        )
        thread.daemon = True
        thread.start()
        
        # 返回任务ID和唯一文件名
        return jsonify({
            "task_id": task_id,
            "message": "翻译任务已开始",
            "download_filename": unique_output_filename,
            "original_filename": file.filename
        })
    
    return jsonify({"error": "只支持DOC和DOCX文件"}), 400

@app.route('/download/<filename>')
def download_file(filename):
    """下载翻译完成的文件"""
    output_path = os.path.join("output", filename)
    if os.path.exists(output_path):
        return send_file(
            output_path,
            as_attachment=True,
            download_name=filename
        )
    else:
        return jsonify({"error": "文件不存在"}), 404



@app.route('/')
def index():
    """主页面"""
    return '''
    <!doctype html>
    <html>
    <head>
        <title>文档翻译工具 - 动态进度版</title>
        <style>
            body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; background-color: #f5f5f5; }
            .container { text-align: center; background-color: white; padding: 30px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
            
            /* 上传区域样式 */
            .upload-area { 
                border: 2px dashed #ddd; 
                border-radius: 8px; 
                padding: 30px 20px; 
                margin: 20px 0; 
                background-color: #fafafa;
                transition: all 0.3s ease;
            }
            .upload-area:hover { 
                border-color: #4CAF50; 
                background-color: #f8fff8;
            }
            .file-input-wrapper { 
                position: relative; 
                display: inline-block; 
                margin: 10px 0;
            }
            .file-input-wrapper input[type="file"] { 
                position: absolute; 
                left: 0; 
                top: 0; 
                opacity: 0; 
                width: 100%; 
                height: 100%; 
                cursor: pointer;
            }
            .file-input-label { 
                display: inline-block; 
                padding: 12px 24px; 
                background-color: #4CAF50; 
                color: white; 
                border-radius: 6px; 
                cursor: pointer; 
                font-size: 16px;
                transition: all 0.3s ease;
            }
            .file-input-label:hover { 
                background-color: #45a049; 
                transform: translateY(-2px);
                box-shadow: 0 4px 8px rgba(0,0,0,0.2);
            }
            .selected-file { 
                margin-top: 10px; 
                font-size: 14px; 
                color: #666;
            }
            
            /* 选项区域样式 */
            .options-area { 
                margin: 25px 0; 
                text-align: center;
            }
            .options-area .option-group { 
                margin: 15px 0; 
            }
            .translation-direction { 
                margin: 15px 0; 
                text-align: center;
            }
            .translation-direction select { 
                padding: 8px 12px; 
                border: 1px solid #ddd; 
                border-radius: 4px; 
                font-size: 14px;
                background-color: white;
            }
            
            /* 按钮区域样式 */
            .button-area { 
                margin: 25px 0; 
                text-align: center;
            }
            
            button { 
                padding: 12px 30px; 
                background-color: #4CAF50; 
                color: white; 
                border: none; 
                border-radius: 6px; 
                cursor: pointer; 
                font-size: 16px;
                font-weight: bold;
                transition: all 0.3s ease;
            }
            button:hover { 
                background-color: #45a049; 
                transform: translateY(-2px);
                box-shadow: 0 4px 8px rgba(0,0,0,0.2);
            }
            button:disabled { 
                background-color: #cccccc; 
                cursor: not-allowed; 
                transform: none;
                box-shadow: none;
            }
            
            .option-group { 
                margin: 20px 0; 
                text-align: center; 
            }
            .option-group label { 
                display: inline-flex; 
                align-items: center; 
                cursor: pointer; 
                font-size: 14px;
                padding: 8px 16px;
                background-color: #f0f0f0;
                border-radius: 4px;
            }
            .option-group input[type="checkbox"] { 
                margin-right: 8px; 
            }
            
            /* 功能特性样式 */
            .features-section { 
                margin-top: 40px; 
                text-align: center;
            }
            .features-toggle { 
                background: none; 
                border: none; 
                color: #666; 
                cursor: pointer; 
                font-size: 14px; 
                text-decoration: underline;
                margin-bottom: 10px;
            }
            .features-toggle:hover { 
                color: #4CAF50;
            }
            .feature-list { 
                text-align: left; 
                margin: 0 auto; 
                max-width: 500px; 
                display: none;
                background-color: #f9f9f9;
                padding: 20px;
                border-radius: 8px;
                border-left: 4px solid #4CAF50;
            }
            .feature-list li { 
                margin: 8px 0; 
                padding-left: 10px;
            }
            .feature-list.show { 
                display: block;
            }
            
            /* 进度条样式 */
            .progress-container { 
                margin: 20px 0; 
                display: none; 
                text-align: left;
                max-width: 500px;
                margin-left: auto;
                margin-right: auto;
            }
            .progress-bar { 
                width: 100%; 
                height: 20px; 
                background-color: #f0f0f0; 
                border-radius: 10px; 
                overflow: hidden; 
                margin: 10px 0;
            }
            .progress-fill { 
                height: 100%; 
                background-color: #4CAF50; 
                width: 0%; 
                transition: width 0.3s ease;
            }
            .progress-text { 
                font-size: 14px; 
                color: #666; 
                margin: 5px 0;
            }
            .progress-details { 
                font-size: 12px; 
                color: #888;
            }
            
            /* 结果区域样式 */
            .result-container { 
                margin: 20px 0; 
                display: none; 
                padding: 20px;
                background-color: #f9f9f9;
                border-radius: 8px;
                border-left: 4px solid #4CAF50;
            }
            .download-btn { 
                background-color: #2196F3; 
                margin: 10px 5px;
            }
            .download-btn:hover { 
                background-color: #1976D2;
            }
            .error-message { 
                color: #f44336; 
                background-color: #ffebee;
                padding: 15px;
                border-radius: 8px;
                border-left: 4px solid #f44336;
                display: none;
                margin: 20px 0;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <h1>文档翻译工具 - 动态进度版</h1>
            <p>上传DOC或DOCX格式的文档，支持英文↔中文双向翻译，实时查看翻译进度</p>
            
            <!-- 上传区域 -->
            <div class="upload-area">
                <form id="uploadForm" enctype="multipart/form-data">
                    <div class="file-input-wrapper">
                        <label class="file-input-label" for="fileInput">
                            📁 选择文档文件
                        </label>
                        <input type="file" name="file" id="fileInput" accept=".doc,.docx" required>
                    </div>
                    <div class="selected-file" id="selectedFile"></div>
                </form>
            </div>
            
            <!-- 选项区域 -->
            <div class="options-area">
                <div class="option-group">
                    <label>
                        <input type="checkbox" name="translate_tables" value="true">
                        翻译表格内容
                    </label>
                </div>
                <div class="translation-direction">
                    <label for="translation_direction">翻译方向：</label>
                    <select name="translation_direction" id="translation_direction">
                        <option value="en_to_zh">英文 → 中文</option>
                        <option value="zh_to_en">中文 → 英文</option>
                    </select>
                </div>
            </div>
            
            <!-- 按钮区域 -->
            <div class="button-area">
                <button type="submit" id="submitBtn">🚀 开始翻译</button>
                <button type="button" id="stopBtn" style="display: none; background-color: #f44336;">⏹️ 停止翻译</button>
            </div>
            
            <!-- 进度显示区域 -->
            <div class="progress-container" id="progressContainer">
                <h3>翻译进度</h3>
                <div class="progress-bar">
                    <div class="progress-fill" id="progressFill"></div>
                </div>
                <div class="progress-text" id="progressText">准备开始...</div>
                <div class="progress-details" id="progressDetails"></div>
            </div>
            
            <!-- 错误信息区域 -->
            <div class="error-message" id="errorMessage"></div>
            
            <!-- 结果区域 -->
            <div class="result-container" id="resultContainer">
                <h3>翻译完成！</h3>
                <p>文档翻译已完成，可以下载翻译后的文件。</p>
                <button class="download-btn" id="downloadBtn">📥 下载翻译文档</button>
                <button onclick="resetForm()">🔄 翻译新文档</button>
            </div>
            
            <!-- 功能特性区域 -->
            <div class="features-section">
                <button class="features-toggle" onclick="toggleFeatures()">📋 查看功能特性</button>
                <div class="feature-list" id="featureList">
                    <h3>功能特性：</h3>
                    <ul>
                        <li>✅ 保留原始文档格式和排版</li>
                        <li>✅ 自动保留图片内容</li>
                        <li>✅ 实时显示翻译进度</li>
                        <li>✅ 动态更新已完成段落数</li>
                        <li>✅ 可选择是否翻译表格内容</li>
                        <li>✅ 支持英文↔中文双向翻译</li>
                        <li>✅ 支持多用户同时使用</li>
                        <li>✅ 自动清理过期任务</li>
                    </ul>
                </div>
            </div>
            
            <p style="margin-top: 20px; color: #666; font-size: 14px;">
                <strong>说明：</strong>默认情况下表格内容不会被翻译，如需翻译表格请勾选上方选项
            </p>
        </div>
        
        <script>
            let currentTaskId = null;
            let progressInterval = null;
            let isPageUnloading = false;
            
            // 页面关闭/刷新时自动停止翻译任务
            window.addEventListener('beforeunload', async function(e) {
                if (currentTaskId && !isPageUnloading) {
                    isPageUnloading = true;
                    
                    // 尝试发送取消请求，但不等待响应（因为页面即将关闭）
                    try {
                        fetch(`/cancel/${currentTaskId}`, {
                            method: 'POST',
                            keepalive: true // 确保请求在页面关闭时也能发送
                        }).catch(() => {
                            // 忽略错误，因为页面正在关闭
                        });
                    } catch (error) {
                        // 忽略错误
                    }
                }
            });
            
            // 文件选择处理
            document.getElementById('fileInput').addEventListener('change', function(e) {
                const selectedFile = document.getElementById('selectedFile');
                if (this.files.length > 0) {
                    selectedFile.textContent = `已选择: ${this.files[0].name}`;
                } else {
                    selectedFile.textContent = '';
                }
            });
            
            // 功能特性折叠控制
            function toggleFeatures() {
                const featureList = document.getElementById('featureList');
                const toggleBtn = document.querySelector('.features-toggle');
                
                if (featureList.classList.contains('show')) {
                    featureList.classList.remove('show');
                    toggleBtn.textContent = '📋 查看功能特性';
                } else {
                    featureList.classList.add('show');
                    toggleBtn.textContent = '📋 隐藏功能特性';
                }
            }
            
            // 开始翻译按钮点击事件
            document.getElementById('submitBtn').addEventListener('click', async function(e) {
                e.preventDefault();
                
                const fileInput = document.getElementById('fileInput');
                const submitBtn = document.getElementById('submitBtn');
                const stopBtn = document.getElementById('stopBtn');
                const progressContainer = document.getElementById('progressContainer');
                const errorMessage = document.getElementById('errorMessage');
                
                if (!fileInput.files[0]) {
                    showError('请选择要翻译的文件');
                    return;
                }
                
                // 禁用提交按钮，显示停止按钮
                submitBtn.disabled = true;
                submitBtn.textContent = '上传中...';
                stopBtn.style.display = 'inline-block';
                
                // 隐藏错误信息
                errorMessage.style.display = 'none';
                
                // 获取表格翻译选项
                const translateTables = document.querySelector('input[name="translate_tables"]').checked;
                // 获取翻译方向
                const translationDirection = document.getElementById('translation_direction').value;
                
                const formData = new FormData();
                formData.append('file', fileInput.files[0]);
                formData.append('translate_tables', translateTables);
                formData.append('translation_direction', translationDirection);
                
                try {
                    const response = await fetch('/upload', {
                        method: 'POST',
                        body: formData
                    });
                    
                    const result = await response.json();
                    
                    if (response.ok) {
                        currentTaskId = result.task_id;
                        // 保存下载文件名到文件输入元素的dataset中
                        fileInput.dataset.downloadFilename = result.download_filename;
                        progressContainer.style.display = 'block';
                        startProgressTracking();
                    } else {
                        showError(result.error || '上传失败');
                        submitBtn.disabled = false;
                        submitBtn.textContent = '🚀 开始翻译';
                        stopBtn.style.display = 'none';
                    }
                } catch (error) {
                    showError('网络错误：' + error.message);
                    submitBtn.disabled = false;
                    submitBtn.textContent = '🚀 开始翻译';
                    stopBtn.style.display = 'none';
                }
            });
            
            // 停止翻译按钮点击事件
            document.getElementById('stopBtn').addEventListener('click', async function(e) {
                e.preventDefault();
                
                if (!currentTaskId) return;
                
                const stopBtn = document.getElementById('stopBtn');
                stopBtn.disabled = true;
                stopBtn.textContent = '停止中...';
                
                try {
                    const response = await fetch(`/cancel/${currentTaskId}`, {
                        method: 'POST'
                    });
                    
                    if (response.ok) {
                        // 停止进度跟踪
                        if (progressInterval) {
                            clearInterval(progressInterval);
                            progressInterval = null;
                        }
                        
                        // 重置界面
                        resetTranslationUI();
                        
                        // 显示取消成功消息
                        showError('翻译任务已取消');
                    } else {
                        showError('停止翻译失败');
                        stopBtn.disabled = false;
                        stopBtn.textContent = '⏹️ 停止翻译';
                    }
                } catch (error) {
                    showError('停止翻译时发生错误：' + error.message);
                    stopBtn.disabled = false;
                    stopBtn.textContent = '⏹️ 停止翻译';
                }
            });
            
            function startProgressTracking() {
                if (progressInterval) {
                    clearInterval(progressInterval);
                }
                
                progressInterval = setInterval(async () => {
                    if (!currentTaskId) return;
                    
                    try {
                        const response = await fetch(`/progress/${currentTaskId}`);
                        const progress = await response.json();
                        
                        if (response.ok) {
                            updateProgressDisplay(progress);
                            
                            // 检查是否完成、出错或被取消
                            if (progress.progress === 100 || progress.error || progress.cancelled) {
                                clearInterval(progressInterval);
                                
                                if (progress.error) {
                                    showError('翻译失败：' + progress.error);
                                } else if (progress.cancelled) {
                                    // 任务被取消，不需要显示错误，因为用户已经知道
                                    resetTranslationUI();
                                } else {
                                    showResult();
                                }
                            }
                        } else {
                            showError('获取进度失败');
                            clearInterval(progressInterval);
                        }
                    } catch (error) {
                        console.error('进度查询错误:', error);
                    }
                }, 1000); // 每秒查询一次进度
            }
            
            function updateProgressDisplay(progress) {
                const progressFill = document.getElementById('progressFill');
                const progressText = document.getElementById('progressText');
                const progressDetails = document.getElementById('progressDetails');
                
                progressFill.style.width = progress.progress + '%';
                progressText.textContent = `翻译进度：${progress.progress}%`;
                
                if (progress.total > 0) {
                    progressDetails.textContent = `已完成 ${progress.current} / ${progress.total} 个段落`;
                } else {
                    progressDetails.textContent = '正在分析文档...';
                }
            }
            
            function showResult() {
                const resultContainer = document.getElementById('resultContainer');
                const downloadBtn = document.getElementById('downloadBtn');
                
                resultContainer.style.display = 'block';
                
                downloadBtn.onclick = function() {
                    // 使用服务器返回的唯一文件名
                    const downloadFilename = document.getElementById('fileInput').dataset.downloadFilename;
                    if (downloadFilename) {
                        window.location.href = `/download/${downloadFilename}`;
                    }
                };
            }
            
            function showError(message) {
                const errorMessage = document.getElementById('errorMessage');
                const submitBtn = document.getElementById('submitBtn');
                
                errorMessage.textContent = message;
                errorMessage.style.display = 'block';
                submitBtn.disabled = false;
                submitBtn.textContent = '上传并翻译';
            }
            
            function resetTranslationUI() {
                const uploadForm = document.getElementById('uploadForm');
                const progressContainer = document.getElementById('progressContainer');
                const resultContainer = document.getElementById('resultContainer');
                const errorMessage = document.getElementById('errorMessage');
                const submitBtn = document.getElementById('submitBtn');
                const stopBtn = document.getElementById('stopBtn');
                
                uploadForm.reset();
                progressContainer.style.display = 'none';
                resultContainer.style.display = 'none';
                errorMessage.style.display = 'none';
                submitBtn.disabled = false;
                submitBtn.textContent = '🚀 开始翻译';
                stopBtn.style.display = 'none';
                stopBtn.disabled = false;
                stopBtn.textContent = '⏹️ 停止翻译';
                
                currentTaskId = null;
                if (progressInterval) {
                    clearInterval(progressInterval);
                    progressInterval = null;
                }
            }
            
            function resetForm() {
                resetTranslationUI();
            }
        </script>
    </body>
    </html>
    '''

if __name__ == '__main__':
    # 创建extract目录
    os.makedirs("extract", exist_ok=True)
    
    # 运行Flask应用
    app.run(debug=False,host='0.0.0.0', port=5008)